<%@ WebHandler Language="C#" Class="GalleryImage" %>

using System;
using System.Web;
using System.IO;
using System.Drawing;
using WebComponents;

public class GalleryImage : IHttpHandler
{
    public bool IsReusable
    { get { return true; } }

    public void ProcessRequest(HttpContext Context)
    {
        try
        {
            // Writing an image to output stream
            Context.Response.ContentType = "image/jpg";

            string FileUrl = "";
            string FilePath = "";

            FileUrl = ConvertType.ToString(Context.Request.Params["FileUrl"]);

            FilePath = Context.Server.MapPath(FileUrl.Trim());

            // 'thumbnail' means we are requesting a thumbnail
            if (Context.Request["Size"] != null)
            {
                float size = ConvertType.ToFloat(Context.Request.QueryString["Size"]);                

                //float thumbnail = float.Parse(Context.Request["thumbnail"]);
                // Need to load the image, resize it, and stream to the client.
                // Calculate the scale so as not to stretch or distort the image.
                Bitmap bmp = new Bitmap(FilePath);
                if (bmp.Width > size || bmp.Height > size)
                {
                    float scale = size / System.Math.Max(bmp.Height, bmp.Width);
                    System.Drawing.Image thumb = bmp.GetThumbnailImage((int)(bmp.Width * scale), (int)(bmp.Height * scale), null, System.IntPtr.Zero);
                    thumb.Save(Context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    bmp.Dispose();
                    thumb.Dispose();
                }
                else
                    ShowImage(FilePath);
            }
            else
            {
                ShowImage(FilePath);
            }
        }
        catch
        {

        }
    }

    public void ShowImage(string FilePath)
    {
        // Stream directly from the file
        // Get the stream and send it out the response
        System.IO.FileStream fs = System.IO.File.Open(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

        const int byteLength = 1024 * 16;
        byte[] bytes = new byte[byteLength];
        while (fs.Read(bytes, 0, byteLength) != 0)
        {
            HttpContext.Current.Response.BinaryWrite(bytes);
        }
        fs.Close();
    }
}


